package com.github.hiling.auth.mapper;

import com.github.hiling.auth.model.RevokeToken;
import com.github.hiling.auth.model.RefreshToken;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Author by hiling, Date on 10/12/2018.
 */
public interface RefreshTokenMapper {

    @Select("""
            select
                id,
                `client_id` as clientId,
                `user_id` as userId,
                `refresh_token` as refreshToken,
                `expires_in` as expiresIn,
                `create_time` as createTime,
                `last_used_time` as lastUsedTime
            from oauth_refresh_token
            where refresh_token = #{refreshToken}
            """)
    RefreshToken getByRefreshToken(@Param("refreshToken") String refreshToken);

    @Select("""
            <script>
                <foreach collection="list" item="item" index="index" separator="union all">
                        select refresh_token as refreshToken
                        from oauth_refresh_token
                        where client_id = #{item.clientId}
                        <if test="item.userId != null">
                            and user_id = #{item.userId}
                        </if>
                        <![CDATA[ and create_time  < #{item.time} ]]>
                    </foreach>
            </script>
            """)
    List<String> getRevokeRefreshToken(List<RevokeToken> list);

    @Insert("""
            insert into oauth_refresh_token
            (
               `client_id`,
                `user_id`,
                `refresh_token`,
                `expires_in`,
                `create_time`,
                `last_used_time`
            )
            values
            (
                #{clientId},
                #{userId},
                #{refreshToken},
                #{expiresIn},
                #{createTime},
                #{lastUsedTime}
            )
            """)
    int insert(RefreshToken refreshToken);

    @Update("update oauth_refresh_token set last_used_time = #{lastUsedTime} where id = #{id}")
    int updateLastUsedTimeById(@Param("id") Long id, @Param("lastUsedTime") LocalDateTime lastUsedTime);

    @Delete("""
            <script>
                delete from oauth_refresh_token where refresh_token in
                <foreach item="refreshToken" index="index" collection="refreshTokenList" open="(" separator="," close=")">
                    #{refreshToken}
                </foreach>
            </script>
            """)
    void batchDeleteByRefreshToken(@Param("refreshTokenList") List<String> refreshTokenList);

    @Delete("delete from oauth_refresh_token where create_time < date_sub(now(), INTERVAL expires_in second);")
    void deleteExpiredRefreshToken();
}
